package link.jfire.socket.socketserver.handler.impl;

import java.nio.charset.Charset;
import javax.annotation.Resource;
import link.jfire.baseutil.collection.ByteCache;
import link.jfire.baseutil.encrypt.RSAUtil;
import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.socket.socketserver.bus.BusinessCommand;
import link.jfire.socket.socketserver.handler.EntryHandler;
import link.jfire.socket.socketserver.storage.Entry;

@Resource
public class ReceiveKeyHandler implements EntryHandler
{
    private Charset charset = Charset.forName("utf8");
    private byte[]  privateKey;
    private Logger  logger  = ConsoleLogFactory.getLogger();
    private byte[]  okCheck = "ok".getBytes(charset);
    private byte[]  sign;
    
    @Override
    public byte interestedDataPacketType()
    {
        return BusinessCommand.SENDKEY;
    }
    
    @Override
    public void handler(Entry entry) throws Exception
    {
        ByteCache data = entry.getBusinessData();
        RSAUtil rsaUtil = new RSAUtil();
        rsaUtil.setPrivateKey(privateKey);
        byte[] key = rsaUtil.decrypt(data.toArray());
        entry.getServerChannelInfo().setKey(key);
        data.clear().putArray(sign);
        entry.getServerChannelInfo().authMsg();
        logger.trace("客户端{}与服务器交换对称加密密钥成功", entry.getServerChannelInfo().getAddress());
    }
    
    public void setPrivateKey(byte[] privateKey)
    {
        this.privateKey = privateKey;
        RSAUtil rsaUtil = new RSAUtil();
        rsaUtil.setPrivateKey(privateKey);
        sign = rsaUtil.sign(okCheck);
    }
}
